<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Common Modules Source: control/contextMenu.js</title>

	<!--[if lt IE 9]>
	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.simplex.css">

</head>

<body>

<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="index.html">Common Modules</a>
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
        </button>
	</div>
	<div class="navbar-collapse collapse" id="topNavigation">
		<ul class="nav navbar-nav">
			
			<li class="dropdown">
				<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="Base.html">Base</a></li><li><a href="Event.html">Event</a></li><li><a href="Html.html">Html</a></li><li><a href="Internal.html">Internal</a></li><li><a href="ol.Overlay.Popup.html">ol.Overlay.Popup</a></li>
				</ul>
			</li>
			
			<li class="dropdown">
				<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="global.html#addClass">addClass</a></li><li><a href="global.html#addListener">addListener</a></li><li><a href="global.html#arrayRemove">arrayRemove</a></li><li><a href="global.html#clear">clear</a></li><li><a href="global.html#create">create</a></li><li><a href="global.html#createHidden">createHidden</a></li><li><a href="global.html#empty">empty</a></li><li><a href="global.html#EventType">EventType</a></li><li><a href="global.html#findListener">findListener</a></li><li><a href="global.html#firstUpperToCase">firstUpperToCase</a></li><li><a href="global.html#get">get</a></li><li><a href="global.html#getChildByTagName">getChildByTagName</a></li><li><a href="global.html#getClass">getClass</a></li><li><a href="global.html#getDomEventKey">getDomEventKey</a></li><li><a href="global.html#getElementsByClassName">getElementsByClassName</a></li><li><a href="global.html#getListeners">getListeners</a></li><li><a href="global.html#getrandom">getrandom</a></li><li><a href="global.html#getStyle">getStyle</a></li><li><a href="global.html#getuuid">getuuid</a></li><li><a href="global.html#hasClass">hasClass</a></li><li><a href="global.html#isObject">isObject</a></li><li><a href="global.html#isString">isString</a></li><li><a href="global.html#layerConfigDefautls">layerConfigDefautls</a></li><li><a href="global.html#listen">listen</a></li><li><a href="global.html#listenOnce">listenOnce</a></li><li><a href="global.html#logo">logo</a></li><li><a href="global.html#OL_Style_Type">OL_Style_Type</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeClass">removeClass</a></li><li><a href="global.html#removeListener">removeListener</a></li><li><a href="global.html#removeListeners">removeListeners</a></li><li><a href="global.html#setClass">setClass</a></li><li><a href="global.html#splitWords">splitWords</a></li><li><a href="global.html#stamp">stamp</a></li><li><a href="global.html#toBack">toBack</a></li><li><a href="global.html#toFront">toFront</a></li><li><a href="global.html#trim">trim</a></li><li><a href="global.html#unListen">unListen</a></li><li><a href="global.html#unlistenAll">unlistenAll</a></li><li><a href="global.html#unListenByKey">unListenByKey</a></li><li><a href="global.html#upperFirstChart">upperFirstChart</a></li>
				</ul>
			</li>
			
		</ul>
        
            <div class="col-sm-3 col-md-3">
                <form class="navbar-form" role="search">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
                        <div class="input-group-btn">
                            <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
                        </div>
                    </div>
                </form>
            </div>
        
	</div>

</div>
</div>


<div class="container" id="toc-content">
<div class="row">

	
	<div class="col-md-12">
	
		<div id="main">
			

		<h1 class="page-title">Source: control/contextMenu.js</h1>
    
<section>
    <article>
        <pre
            class="sunlight-highlight-javascript linenums">/**
 * @desc 右键功能(迁移自项目扩展)
 */
import {
  ol
} from '../constants'
import '../asset/scss/contextMenu.scss'
import {BASE_CLASS_NAME} from '../constants'
import * as htmlUtils from '../utils/domUtils'
import * as Events from '../event/Events'
import Observable from '../utils/observable-emit'
import mixin from '../utils/mixin'
import cloneDeep from 'lodash/cloneDeep'
ol.control.ContextMenu = function (params = {}) {
  this.options = params

  /**
   * 地图容器
   * @type {null}
   */
  this.mapContent = null

  /**
   * 鼠标右键的位置
   * @type {Array}
   */
  this.pixel = []

  /**
   * width
   * @type {number}
   */
  this.itemWidth = (typeof this.options['itemWidth'] === 'number' ? this.options['itemWidth'] : 160)

  /**
   * height
   * @type {number}
   */
  this.itemHeight = (typeof this.options['itemHeight'] === 'number' ? this.options['itemHeight'] : 30)

  /**
   * className
   * @type {string}
   */
  this.className_ = (this.options.className !== undefined ? this.options.className : 'gmap-context-menu-content')

  /**
   * @private
   * @type {Element}
   */
  this.element_ = htmlUtils.create('div', (this.className_ + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE))
  this.element_.style.display = 'none'
  ol.control.Control.call(this, {
    element: this.element_,
    target: this.options['target']
  })
  Observable.call(this)
}

ol.inherits(ol.control.ContextMenu, ol.control.Control)
mixin(ol.control.ContextMenu, Observable)

/**
 * 初始化dom
 * @param items
 */
ol.control.ContextMenu.prototype.initDomInternal = function (items) {
  this.htmlUtils(items, '', this.element_)
  if (this.getMap()) {
    this.mapContent = this.getMap().getViewport()
    Events.listen(this.mapContent, 'contextmenu', this.mouseDownHandle_, this)
  }
}

/**
 * 初始化事件
 * @param event
 * @private
 */
ol.control.ContextMenu.prototype.mouseDownHandle_ = function (event) {
  let that = this
  event.stopPropagation()
  event.preventDefault()
  if (event.button === 2) {
    that.pixel = this.getMap().getEventPixel(event)
    this.dispatch('before-show', event)
    window.setTimeout(() => {
      that.show(that.pixel)
      that.dispatch('show', event)
    }, 50)
  }
  Events.listen(event.target, 'mousedown', function () {
    that.hide()
    that.dispatch('hide', event)
  }, this, true)
}

/**
 * showMenu
 * @param position
 */
ol.control.ContextMenu.prototype.show = function (position) {
  this.element_.style.display = 'block'
  this.element_.style.top = position[1] + 'px'
  this.element_.style.left = position[0] + 'px'
  let aDoc = this.getMap().getSize()
  let maxWidth = aDoc[0] - this.element_.offsetWidth
  let maxHeight = aDoc[1] - this.element_.offsetHeight
  if (this.element_.offsetTop > maxHeight) {
    this.element_.style.top = maxHeight + 'px'
  }
  if (this.element_.offsetLeft > maxWidth) {
    this.element_.style.left = maxWidth + 'px'
  }
}

/**
 * hideMenu
 */
ol.control.ContextMenu.prototype.hide = function () {
  this.element_.style.display = 'none'
  this.pixel = []
}

/**
 * html处理工具
 * @param items
 * @param index
 * @param content
 * @param isOffset
 * @returns {*}
 */
ol.control.ContextMenu.prototype.htmlUtils = function (items, index, content, isOffset) {
  let that = this
  let ulList = null
  if (items &amp;&amp; Array.isArray(items) &amp;&amp; items.length > 0) {
    ulList = htmlUtils.create('ul', this.className_ + '-ul' + index + '-inner', content, this.className_ + '-ul' + index + '-inner')
    if (isOffset) {
      ulList.style.position = 'absolute'
      ulList.style.top = '0px'
      ulList.style.left = this.itemWidth + 20 + 'px'
    }
    items.forEach((item, index_) => {
      if (item &amp;&amp; item['name'] &amp;&amp; item['alias']) {
        let numList = index + '-' + index_
        let li_ = htmlUtils.create('li', this.className_ + '-li-' + numList + '-inner', ulList, this.className_ + '-li-' + numList + '-inner')
        li_.style.width = this.itemWidth + 'px'
        li_.style.height = this.itemHeight + 'px'
        li_.style.lineHeight = this.itemHeight + 'px'
        li_.setAttribute('data-name', item['alias'])
        Events.listen(li_, 'click', function (event) {
          that.handleItemClick_(event, item)
        }, this)
        if (item['icon']) {
          let span_ = htmlUtils.create('span', 'li-icon-content', li_)
          if (item['iconType'] === 'iconfont') {
            let fontName = item['fontName'] ? item['fontName'] : 'iconfont'
            htmlUtils.addClass(span_, fontName + ' ' + item['icon'])
            if (item['iconColor']) {
              span_.style.color = item['iconColor']
            }
          } else {
            span_.style.background = 'url(' + item['icon'] + ') 0px 0px no-repeat'
          }
        }
        let name_ = htmlUtils.create('span', 'li-name-content', li_)
        name_.innerHTML = item['name']
        if (item['showLine']) {
          li_.style.borderBottom = '1px solid #CCCCCC'
        }
        if (item['items']) {
          this.htmlUtils(item['items'], numList, li_, true)
          Events.listen(li_, 'mouseenter', this.handleItemMouseOver_, this)
          Events.listen(li_, 'mouseleave', this.handleItemMouseOut_, this)
        }
      }
    })
  }
  return ulList
}

/**
 * 更新面板元素
 * @param type
 * @param item
 * @param items
 * @private
 */
ol.control.ContextMenu.prototype.updateElement_ = function (type, item, items) {
  let child_ = htmlUtils.get(this.className_ + '-ul' + '-inner')
  let cloneItems = cloneDeep(this.options['items'])
  let afterItems = null
  switch (type) {
    case 'pop': // 移除最后一个
      this.element_.removeChild(child_)
      afterItems = cloneItems.pop()
      this.htmlUtils(cloneItems, '', this.element_)
      break
    case 'push': // 数组的末尾添加新的元素
      this.element_.removeChild(child_)
      afterItems = cloneItems = cloneItems.push(item)
      this.htmlUtils(cloneItems, '', this.element_)
      break
    case 'shift': // 删除数组的第一个元素
      this.element_.removeChild(child_)
      afterItems = cloneItems.shift()
      this.htmlUtils(cloneItems, '', this.element_)
      break
    case 'unshift': // 在数组的开头添加新元素
      this.element_.removeChild(child_)
      afterItems = cloneItems = cloneItems.unshift(item)
      this.htmlUtils(cloneItems, '', this.element_)
      break
    case 'reverse':
      this.element_.removeChild(child_)
      afterItems = cloneItems.reverse()
      this.htmlUtils(cloneItems, '', this.element_)
      break
    default:
      this.element_.removeChild(child_)
      afterItems = items
      this.htmlUtils(items, '', this.element_)
  }
  return afterItems
}

/**
 * 获取鼠标右键位置的像素坐标
 * @returns {ol.Pixel|*|Array}
 */
ol.control.ContextMenu.prototype.getCurrentPixel = function () {
  return this.pixel
}

/**
 * 获取鼠标点击位置的地图坐标
 * @returns {ol.Coordinate}
 */
ol.control.ContextMenu.prototype.getCurrentCoordinates = function () {
  return (this.getMap().getCoordinateFromPixel(this.getCurrentPixel()))
}

/**
 * 处理列表点击事件
 * @param event
 * @param item
 * @private
 */
ol.control.ContextMenu.prototype.handleItemClick_ = function (event, item) {
  if (item &amp;&amp; item['callback'] &amp;&amp; typeof item['callback'] === 'function') {
    item['callback'](event, {
      source: item,
      pixel: this.getCurrentPixel(),
      coordinates: this.getCurrentCoordinates()
    })
  }
  this.dispatch('item-click', event, {
    source: item,
    pixel: this.getCurrentPixel(),
    coordinates: this.getCurrentCoordinates()
  })
  window.setTimeout(() => {
    this.hide()
  }, 50)
}

/**
 * 处理鼠标移入事件
 * @param event
 * @private
 */
ol.control.ContextMenu.prototype.handleItemMouseOver_ = function (event) {
  if (event.target &amp;&amp; event.target.childNodes) {
    let elements = Array.prototype.slice.call(event.target.childNodes, 0)
    if (elements &amp;&amp; elements.length > 0) {
      elements.every(ele => {
        if (ele &amp;&amp; ele.nodeName.toLowerCase() === 'ul') {
          ele.style.display = 'block'
          return false
        } else {
          return true
        }
      })
    }
  }
}

/**
 * 处理鼠标移出事件
 * @param event
 * @private
 */
ol.control.ContextMenu.prototype.handleItemMouseOut_ = function (event) {
  if (event.target &amp;&amp; event.target.childNodes) {
    let elements = Array.prototype.slice.call(event.target.childNodes, 0)
    if (elements &amp;&amp; elements.length > 0) {
      elements.every(ele => {
        if (ele &amp;&amp; ele.nodeName.toLowerCase() === 'ul') {
          ele.style.display = 'none'
          return false
        } else {
          return true
        }
      })
    }
  }
}

/**
 * setMap
 * @param map
 */
ol.control.ContextMenu.prototype.setMap = function (map) {
  ol.control.Control.prototype.setMap.call(this, map)
  if (map &amp;&amp; map instanceof ol.Map) {
    this.initDomInternal(this.options['items'])
  }
}

/**
 * 移除菜单最后一项
 */
ol.control.ContextMenu.prototype.pop = function () {
  return this.updateElement_('pop')
}

/**
 * 向菜单末尾添加一项
 * @param item
 */
ol.control.ContextMenu.prototype.push = function (item) {
  if (item &amp;&amp; typeof item === 'object') {
    return this.updateElement_('push', item)
  } else {
    throw new Error('传入的不是对象')
  }
}

/**
 * 移除菜单第一项
 */
ol.control.ContextMenu.prototype.shift = function () {
  return this.updateElement_('shift')
}

/**
 * 倒叙菜单
 */
ol.control.ContextMenu.prototype.reverse = function () {
  return this.updateElement_('reverse')
}

/**
 * 向菜单开头添加一项
 * @param item
 */
ol.control.ContextMenu.prototype.unshift = function (item) {
  if (item &amp;&amp; typeof item === 'object') {
    return this.updateElement_('unshift', item)
  } else {
    throw new Error('传入的不是对象')
  }
}

/**
 * 更新菜单
 * @param items
 */
ol.control.ContextMenu.prototype.update = function (items) {
  if (items &amp;&amp; Array.isArray(items) &amp;&amp; items.length > 0) {
    this.updateElement_('', '', items)
  } else {
    throw new Error('传入的数组有误！')
  }
}

/**
 * 更新内置配置
 * @param items
 */
ol.control.ContextMenu.prototype.updateOption = function (items) {
  if (items &amp;&amp; Array.isArray(items) &amp;&amp; items.length > 0) {
    this.options['items'] = items
    this.updateElement_('', '', items)
  } else {
    throw new Error('传入的数组有误！')
  }
}

let olControlContextMenu = ol.control.ContextMenu
export default olControlContextMenu
</pre>
    </article>
</section>





		</div>
	</div>

	<div class="clearfix"></div>

	

</div>
</div>


    <div class="modal fade" id="searchResults">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Search results</h4>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div>


<footer>


	<span class="copyright">
	https://lzw.me.
	</span>

<span class="jsdoc-message">
	Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
	
		on Sun Aug 12th 2018
	
	using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>

<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>

    <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>


<script>
$( function () {
	$( "[id*='$']" ).each( function () {
		var $this = $( this );

		$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
	} );

	$( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
		var $this = $( this );

		var example = $this.find( "code" );
		exampleText = example.html();
		var lang = /{@lang (.*?)}/.exec( exampleText );
		if ( lang && lang[1] ) {
			exampleText = exampleText.replace( lang[0], "" );
			example.html( exampleText );
			lang = lang[1];
		} else {
			var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
			lang = langClassMatch ? langClassMatch[1] : "javascript";
		}

		if ( lang ) {

			$this
			.addClass( "sunlight-highlight-" + lang )
			.addClass( "linenums" )
			.html( example.html() );

		}
	} );

	Sunlight.highlightAll( {
		lineNumbers : true,
		showMenu : true,
		enableDoclinks : true
	} );

	$.catchAnchorLinks( {
        navbarOffset: 10
	} );
	$( "#toc" ).toc( {
		anchorName  : function ( i, heading, prefix ) {
			return $( heading ).attr( "id" ) || ( prefix + i );
		},
		selectors   : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
		showAndHide : false,
		smoothScrolling: true
	} );

	$( "#main span[id^='toc']" ).addClass( "toc-shim" );
	$( '.dropdown-toggle' ).dropdown();

    $( "table" ).each( function () {
      var $this = $( this );
      $this.addClass('table');
    } );

} );
</script>



<!--Navigation and Symbol Display-->


<!--Google Analytics-->



    <script type="text/javascript">
        $(document).ready(function() {
            SearcherDisplay.init();
        });
    </script>


</body>
</html>
